<template>
  <div id="login_form">
    <el-dialog title="user/register" width="400px" center :visible.sync="toLogin">
      <el-form :model="login_form" :rules="rules" status-icon ref="ruleForm" class="ruleForm">
      <span style="text-align: center">
        <el-button type="text" size="small" round @click="ver=false;operation='登录'">登录</el-button>
        <el-button type="text" size="small" round @click="ver=true;operation='注册'">注册</el-button></span>

        <el-form-item prop="email">
          <el-input prefix-icon="el-icon-user-solid" placeholder="请输入邮箱" v-model="login_form.email"></el-input>
        </el-form-item>

        <el-form-item prop="passwd">
          <el-input
              prefix-icon="el-icon-view"
              type="password"
              placeholder="请输入密码"
              v-model="login_form.passwd"
          ></el-input>
        </el-form-item>

        <el-form-item v-if="ver" prop="ver_passwd">
          <el-input
              prefix-icon="el-icon-view"
              type="password"
              placeholder="请再次确认密码"
              v-model="login_form.ver_passwd"
          ></el-input>
        </el-form-item>

        <el-form-item v-if="ver" prop="verify">
          <el-input
              prefix-icon="el-icon-message"
              type="text"
              placeholder="请输入验证码"
              v-model="login_form.verify"
              style="width: 65%"
          ></el-input>
          <el-button type="primary" :disabled='ver_send' @click="sendCode"
                     style="text-align: center;margin-left: 10px;">{{ ver_button }}
          </el-button>
        </el-form-item>

        <el-form-item>
          <el-button size="medium" type="primary" :loading="loading" @click="Login" style="width:100%;">{{
              operation
            }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {mapActions} from "vuex";

export default {
  name: "login_form",
  data() {
    // 用户名的校验方法
    let validateEmail = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请输入邮箱"));
      }
      // 用户名以字母开头,长度在5-16之间,允许字母数字下划线
      const emailRule = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
      if (emailRule.test(value)) {
        this.$refs.ruleForm.validateField("checkPass");
        this.ver_send = false;
        return callback();
      } else {
        return callback(new Error("邮箱格式错误"));
      }
    };
    // 密码的校验方法
    let validatePasswd = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请输入密码"));
      }
      // 密码以字母开头,长度在6-18之间,允许字母数字和下划线
      const passwordRule = /^\w{5,17}$/;
      if (passwordRule.test(value)) {
        this.$refs.ruleForm.validateField("checkPass");
        return callback();
      } else {
        return callback(
            new Error("长度6-18之间,允许字母数字和下划线")
        );
      }
    };

    let validateVerPasswd = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请确认密码"));
      }
      // 密码以字母开头,长度在6-18之间,允许字母数字和下划线
      if (value === this.login_form.passwd) {
        this.$refs.ruleForm.validateField("checkPass");
        return callback();
      } else {
        return callback(
            new Error("密码不匹配")
        );
      }
    };
    let validateVerify = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请输入验证码"));
      }
      // 密码以字母开头,长度在6-18之间,允许字母数字和下划线
      const passwordRule = /^\w+$/;
      if (passwordRule.test(value)) {
        this.$refs.ruleForm.validateField("checkPass");
        return callback();
      } else {
        return callback(
            new Error("输入码格式错误")
        );
      }
    };
    return {
      login_form: {
        email: "",
        passwd: "",
        ver_passwd: "",
        verify: ""
      },
      ver: false,
      ver_button: "发送验证码",
      ver_send: true,
      loading: false,
      operation: "登录",
      flag: true,
      // 用户信息校验规则,validator(校验方法),trigger(触发方式),blur为在组件 Input 失去焦点时触发
      rules: {
        email: [{validator: validateEmail, trigger: "blur"}],
        passwd: [{validator: validatePasswd, trigger: "blur"}],
        ver_passwd: [{validator: validateVerPasswd, trigger: "blur"}],
        verify: [{validator: validateVerify, trigger: "blur"}]
      }
    };
  },
  computed: {
    // 获取vuex中的showLogin，控制登录组件是否显示
    toLogin: {
      get() {
        return this.$store.getters.getToLogin;
      },
      set(val) {
        this.$refs["ruleForm"].resetFields();
        this.ver_button = "发送验证码";
        this.setToLogin(val);
      }
    }
  },
  methods: {
    sendCode() {
      let email = this.login_form.email
      if (this.validateEmail(email)) {
        // console.log(tel)
        this.$store
            .dispatch("Verify", this.login_form)
            .then(response => {
              let code = response.data.code;
              if (code === 200) {
                let time = 60
                this.ver_button = '已发送'
                this.ver_send = true
                if (this.flag) {
                  this.flag = false;
                  let timer = setInterval(() => {
                    time--;
                    this.ver_button = time + ' 秒'
                    if (time === 0) {
                      clearInterval(timer);
                      this.ver_button = '重新获取'
                      this.ver_send = false
                      this.flag = true;
                    }
                  }, 1000)
                }
              } else if (code == 501) {
                this.ver = false;
                this.alert('用户名已存在');
              }
            })
      }
    },
    validateEmail(email) {
      if (email === "") {
        return false;
      }
      // 用户名以字母开头,长度在5-16之间,允许字母数字下划线
      const emailRule = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
      return emailRule.test(email);
    },
    ...mapActions(["setUser", "setToLogin", "setToken"]),
    Login() {
      // 通过element自定义表单校验规则，校验用户输入的用户信息
      this.$refs["ruleForm"].validate(valid => {
        //如果通过校验开始登录
        if (valid) {
          this.loading = true;
          if (this.ver === false) {
            this.$store
                .dispatch("Login", this.login_form)
                .then(response => {
                  this.loading = false;
                  let code = response.data.code;
                  let token = response.data.token;
                  let message = response.data.message;
                  // let msg = response.data.message;
                  if (code == 200) {
                    this.setToLogin(false);
                    this.setUser(this.login_form.email);
                    this.setToken(token);
                    localStorage.setItem("token", token);
                    location.reload();
                    return true
                  } else if (code === 500 && message == "用户名不存在") {
                    this.ver = true;
                    this.alert('用户名不存在')
                    this.sendCode();
                  } else {
                    this.alert('用户名或密码错误');
                    return false
                  }
                })
                .catch(() => {
                  this.loading = false;
                });
          } else {
            this.$store
                .dispatch("Register", this.login_form)
                .then(response => {
                  this.loading = false;
                  let code = response.data.code;
                  let token = response.data.token;
                  let message = response.data.message
                  if (code === 200) {
                    localStorage.setItem("token", token);
                    this.setToLogin(false);
                    this.setUser(this.login_form.email)
                    this.setToken(token);
                    location.reload();
                    return true
                  } else if (code == 501) {
                    console.log(response.data)
                    console.log(message)
                    this.ver = false;
                    this.alert('用户名已存在');
                  } else {
                    return false
                    // this.$router.push({
                    //   path: "/error",
                    //   query: {message: response.data.message}
                    // });
                  }
                })
                .catch(() => {
                  this.loading = false;
                });
          }
        } else {
          // eslint-disable-next-line no-console
          console.log("参数验证不合法！");
          return false;
        }
      })
    },
    alert(message) {
      this.$alert(message, {
        confirmButtonText: '确定'
      });
    }
  }
};
</script>
<style>
</style>